<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>分割关系</span>
            </div>
          </div>

          <div class="marginBottom5 marginTop15">
            <div class="mainor_te">
              <el-button @click="(addedFormVisible = true), (type = 1)"
                >新增关系</el-button
              >
            </div>

            <el-form
              :inline="true"
              :model="form"
              class="demo-form-inline"
              ref="userListFrom"
              label-width="90px"
            >
              <el-form-item label="白条名称：" prop="goods_spu_id">
                <change-goods-input
                  isInventory
                  ref="changeGoodsInput"
                  @clear="
                    () => {
                      this.form.goods_spu_id = '';
                    }
                  "
                  @sendValue="
                    data => {
                      this.form.goods_spu_id = data.id;
                    }
                  "
                ></change-goods-input>
              </el-form-item>

              <el-form-item>
                <el-button
                  class="reset marginLeft10"
                  type="primary"
                  @click="
                    $refs['userListFrom'].resetFields(),
                      (createTime = []),
                      ($refs['changeGoodsInput'].name = '')
                  "
                  >重置</el-button
                >
                <el-button
                  type="primary"
                  @click="getArticleList"
                  :loading="listLoading"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>

        <div class="main_table" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="datalist"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
          >
            <el-table-column label="白条名称" max-width="120" prop="name">
              <template slot-scope="scope">
                {{ scope.row.name }}【{{ scope.row.unit }}】
              </template>
            </el-table-column>
            <el-table-column label="单位" width="90" prop="unit" />
            <el-table-column
              label="子料信息"
              min-width="220"
              prop="goods_content"
              align="center"
            >
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.child_goods_spu_ids"
                  :key="index"
                  type="success"
                  style="margin: 2px 3px"
                  >{{ item.name }}【{{ item.unit }}】</el-tag
                >
              </template>
            </el-table-column>

            <el-table-column
              label="创建时间"
              show-overflow-tooltip
              max-width="160"
              prop="created_at"
            >
              <template slot-scope="scope">{{
                parseTime(scope.row.created_at)
              }}</template>
            </el-table-column>

            <el-table-column
              label="管理操作"
              align="left"
              fixed="right"
              width="160"
              class-name="main_hei"
              label-class-name="main-center"
            >
              <template slot-scope="scope">
                <el-link type="primary" @click="editGroup(scope.row)"
                  >编辑</el-link
                >
                <el-link type="danger" @click="delGroup(scope.row)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 新增关系 -->
        <el-dialog
          width="35%"
          :title="type == 1 ? '新增关系' : '编辑关系'"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="closeDia(1)"
          :visible.sync="addedFormVisible"
          class="main_dialog dialog550"
        >
          <el-form
            :inline="false"
            :model="info"
            class="demo-form-inline"
            ref="userListFrom1"
            label-width="140px"
          >
            <el-form-item label="商品：" prop="">
              <el-autocomplete
                v-if="type == 1"
                v-model="info.value"
                ref="searchSelect"
                class="wid240 main_comm"
                @clear="clearData"
                :fetch-suggestions="
                  (queryString, cb) => {
                    querySearchAsync(queryString, cb);
                  }
                "
                placeholder="商品/助记码/编码"
                clearable
                :trigger-on-focus="false"
                value-key="name"
                @select="
                  item => {
                    handleSelect(item, 1);
                  }
                "
              >
              </el-autocomplete>
              <el-input
                v-if="type == 2"
                v-model.trim="info.value"
                placeholder="商品"
                clearable
                :disabled="true"
                class="wid240"
              ></el-input>
            </el-form-item>

            <el-form-item label="单位：" prop="">
              <el-input
                v-model.trim="info.unit"
                placeholder="单位"
                clearable
                :disabled="true"
                class="wid240"
              ></el-input>
            </el-form-item>

            <el-form-item label="选择子料：" prop="">
              <el-autocomplete
                v-model="info.name"
                ref="childSelect"
                class="wid240 main_comm"
                @clear="clearchild"
                :fetch-suggestions="
                  (queryString, cb) => {
                    childSelectAsync(queryString, cb);
                  }
                "
                placeholder="商品/助记码/编码"
                clearable
                value-key="name"
                :trigger-on-focus="false"
                @select="
                  item => {
                    handleSelect(item, 2);
                  }
                "
              >
              </el-autocomplete>

              <el-input
                v-model.trim="info.child_unit"
                placeholder="单位"
                clearable
                :disabled="true"
                class="wid80"
              ></el-input>

              <el-button type="primary" @click="handle">确认(回车)</el-button>
            </el-form-item>

            <!-- 表格 -->
            <div class="main_table">
              <el-table
                ref="pleTable"
                :data="info.list"
                element-loading-text="加载中"
                fit
                border
                highlight-current-row
              >
                <el-table-column label="序号" width="70">
                  <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>

                <el-table-column
                  label="商品名称"
                  prop="name"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <div v-if="type == 1">{{ scope.row.name }}</div>
                    <div v-else>
                      {{ scope.row.name }}【{{ scope.row.unit }}】
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  label="单位"
                  prop="unit"
                  width="70"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  label="管理操作"
                  align="left"
                  width="150"
                  class-name="main_hei"
                  label-class-name="main-center"
                >
                  <template slot-scope="scope">
                    <el-link type="danger" @click="delchild(scope)"
                      >删除</el-link
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="(addedFormVisible = false), sysncClose()"
              >取 消</el-button
            >
            <el-button type="primary" @click="setupmine" v-repeatClick
              >保 存</el-button
            >
          </div>
        </el-dialog>

        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const shuju = {
  list: {
    name: "",
    unit: "",
    id: ""
  }
};

import {
  split_index,
  split_add,
  split_edit,
  split_del
} from "@/api/warehouse/warehouseAllocation";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";
import { goods_getAllGoodsSpu,goods_getGoodsSpu } from "@/api/currency";

export default {
  data() {
    return {
      parseTime,
      current: {
        page: 1,
        per_page: 20
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      datalist: [],
      listLoading: false,
      // 搜索
      form: {
        goods_spu_id: ""
      },
      info: {
        goods_spu_id: "", //商品spuid
        child_spu_ids: "", //子料spuid
        value: "", //商品名称
        unit: "", //展示商品单位名称
        unit_id: "", //单位id
        name: "", //子料商品名称
        child_unit: "", //展示单位名称
        child_id: "", //展示id
        list: [] //子料列表数据
      },
      addedFormVisible: false,
      type: 1,
      id: "" //编辑保存传的id
    };
  },
  created() {
    // 列表
    this.split_index();
  },
  methods: {
    // 同步弹窗关闭
    sysncClose() {
      this.info = {
        goods_spu_id: "", //商品spuid
        child_spu_ids: "", //子料spuid
        value: "", //商品名称
        unit: "", //展示商品单位名称
        unit_id: "", //单位id
        name: "", //子料商品名称
        child_unit: "", //展示单位名称
        child_id: "", //展示id
        list: [] //子料列表数据
      };
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      goods_getGoodsSpu(data).then(res => {
        if (res.errcode == 0) {
          res.data.goods.map(e => {
            let title = e.spu_name ? e.spu_name.title : "";
            e.name = e.goods.name + "【" + title + "】";
          });
          let results = res.data.goods;
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    //子料商品搜索
    childSelectAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      goods_getGoodsSpu(data).then(res => {
        if (res.errcode == 0) {
          res.data.goods.map(e => {
            let title = e.spu_name ? e.spu_name.title : "";
            e.name = e.goods.name + "【" + title + "】";
          });
          let results = res.data.goods;
          if (this.$refs.childSelect) {
            this.$refs.childSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.split_index();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.split_index();
    },
    //改变分页
    changePage(page) {
      this.current.page = page;
      this.split_index();
    },
    //编辑分割关系
    editGroup(row) {
      this.addedFormVisible = true;
      this.info.value = row.name + `【${row.unit}】`;
      this.info.unit = row.unit;
      this.info.list = JSON.parse(JSON.stringify(row.child_goods_spu_ids));
      this.info.goods_spu_id = row.goods_spu_id;
      this.info.unit_id = row.unit_id;
      this.id = row.id;
      this.type = 2;
    },
    // 删除
    delchild(scope) {
      let index = scope.$index;
      this.info.list.splice(index, 1);
    },
    //删除分割关系
    delGroup(row) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { id: row.id }
      );
      split_del(data).then(res => {
        if (res.errcode == 0) {
          this.$message.success("删除成功");
          this.split_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //关闭弹窗
    closeDia() {
      this.$nextTick(() => {
        this.sysncClose();
      });
      this.addedFormVisible = false;
    },
    // 商品选择
    handleSelect(item, type) {
      if (type == 1) {
        let txt = item.spu_unit ? item.spu_unit.title : "";
        this.info.value = item.name;
        this.info.unit = txt; //展示单位
        this.info.unit_id = item.unit; //单位id
        this.info.goods_spu_id = item.id;
      } else {
        let unit_txt = item.spu_unit ? item.spu_unit.title : "";
        this.info.name = item.name;
        this.info.child_unit = unit_txt; //展示单位
        this.info.child_id = item.unit; //单位id
        this.info.child_spu_ids = item.id;
      }
    },
    //确认回车添加
    handle() {
      let arr = this.info;
      if (arr.unit_id != arr.child_id) {
        this.$message.error("子料的单位必须与白条单位相同");
        this.info.name = "";
        this.info.child_unit = "";
        this.info.child_spu_ids = "";
      } else if (arr.child_spu_ids == arr.goods_spu_id) {
        //二级不能和一级商品相同
        this.$message.error("不可添加相同商品");
        this.info.name = "";
        this.info.child_unit = "";
        this.info.child_spu_ids = "";
      } else {
        //二级不能添加相同商品
        let list = JSON.parse(JSON.stringify(shuju.list));
        list.name = arr.name;
        list.unit = arr.child_unit;
        list.id = arr.child_spu_ids;
        if (this.type == 1) {
          let ind = 0;
          if (this.info.list.length != 0) {
            this.info.list.map(e => {
              if (e.id == arr.child_spu_ids) {
                ind = e.id;
                return;
              }
            });
          }
          if (ind == 0) {
            this.info.list.push(list);
          } else {
            this.$message.error("不可添加相同的子料");
          }
        } else {
          let id = this.info.child_spu_ids;
          let newlist = this.info.list.filter(e => e.id == id);
          if (newlist.length > 0) {
            if (id == newlist[0].id) {
              this.$message.error("不可添加相同的子料");
            }
          } else {
            this.info.list.push(list);
          }
        }
        this.info.name = "";
        this.info.child_unit = "";
        this.info.id = "";
      }
    },
    //保存
    setupmine() {
      if (this.type == 1) {
        this.add();
      } else {
        this.edit();
      }
    },
    //添加保存
    add() {
      let ids = [];
      this.info.list.map(e => {
        ids.push(e.id);
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { goods_spu_id: this.info.goods_spu_id, child_ids: ids }
      );
      split_add(data).then(res => {
        if (res.errcode == 0) {
          this.$message.success("新增成功");
          this.addedFormVisible = false;
          this.info = {};
          this.split_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //编辑保存
    edit() {
      let ids = [];
      this.info.list.map(e => {
        ids.push(e.id);
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { goods_spu_id: this.info.goods_spu_id, child_ids: ids, id: this.id }
      );
      split_edit(data).then(res => {
        if (res.errcode == 0) {
          this.$message.success("新增成功");
          this.addedFormVisible = false;
          this.info = {};
          this.split_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 列表
    split_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.form, this.current)) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        this.form,
        this.current
      );
      split_index(data).then(res => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.datalist = res.data.list;
          this.totalCount = res.data.arr.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //清除事件
    clearData() {
      this.info.value = "";
      this.info.goods_spu_id = "";
      this.$refs.searchSelect.activated = false;
    },
    //清除事件
    clearchild() {
      this.info.name = "";
      this.info.child_ids = "";
      this.$refs.childSelect.activated = false;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.el-form-item--small.el-form-item {
  margin-bottom: 12px;
}
.mainsu {
  .mainor_form form {
    width: calc(100% - 100px);
  }
}

// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
}
.maintip {
  text-align: center;
  padding-top: 15px;
  font-size: 18px;
  span {
    display: inline;
    padding: 18px 0;
    color: red;
  }
}
.type1 {
  color: #03a98e;
}
.type2 {
  color: red;
}
// 导入
.importForm {
  display: flex;
  align-items: center;
  justify-content: center;
}
.allot_type_container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  & > div {
    width: 90px;
    height: 90px;
    margin: 10px 0;
    text-align: center;
    line-height: 90px;
    font-size: 14px;
    color: #ccc;
    border: 1px dashed #e6e6e6;
    cursor: pointer;
    &:hover {
      color: #03a98e;
      border-color: #03a98e;
    }
  }
}
.main_dialog_copy {
  /deep/ .el-dialog {
    margin-top: 30vh !important;
  }
}
/deep/.main_table .el-table--small td .cell {
  height: auto;
}

/deep/.el-message-box__wrapper .el-button:focus,
.el-message-box__wrapper .el-button:hover,
.el-dialog__wrapper .el-button:focus,
.el-dialog__wrapper .el-button:hover {
  background: #03a98e;
  border-color: #03a98e;
  color: white;
}
</style>
